<?php


namespace app\shop\controller\group;


use app\BaseController;
use app\shop\common\consts\Consts;
use app\shop\service\order\EvaluateService;
use app\shop\service\order\OrderService;
use think\facade\Db;

class EvaluateController extends BaseController
{
    /**
     * 订单是否需要评价
     * @return \think\response\Json
     */
    public function orderIsNeedEval()
    {
        try {
            $orderId = $this->request->param('order_id', 0, 'int');
            $service = new EvaluateService();
            $result = $service->getOrderEvaluateRemindStatus($orderId);
            if ($result) {
                $service = new EvaluateService();
                $result = $service->setTodayEvaluateRemind($orderId);
            }
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 完成订单待评价
     * @return \think\response\Json
     */
    public function overOrderRemind()
    {
        try {
            $userId = $this->request->middleware('userId');
            $service = new EvaluateService();
            $result = $service->overOrderRemind($userId);
            if ($result) {
                $service = new EvaluateService();
                $result = $service->setTodayEvaluateRemind($result['id']);
            }
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 评价提醒今日已提醒
     * @return \think\response\Json
     */
    public function setEvalRemind()
    {
        try {
            $orderId = $this->request->param('order_id', 0, 'int');
            $service = new EvaluateService();
            $result = $service->setTodayEvaluateRemind($orderId);
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单评价
     * @return \think\response\Json
     */
    public function evaluate()
    {
        Db::startTrans();
        try {
            $orderId = $this->request->param('id', 0, 'int');
            $evaluateInfo = $this->request->param('evaluate_info', '', ['trim']);
            if (!is_array($evaluateInfo)) {
                throw new \Exception('参数错误');
            }
            $userInfo = $this->request->middleware('userInfo');
            // 获取登陆者身份  根据身份判断
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::CUSTOMER_ID) {
                throw new \Exception('只有客户可以评价');
            }
            OrderService::evaluateOrder($orderId, $evaluateInfo);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }
}